package controllers

import (
	"github.com/astaxie/beego/logs"
	"github.com/zw2582/zm_go_lib/controllers"
	"github.com/zw2582/zm_go_lib/helpers"
	"kitalk/models"
	"kitalk/services"
)

type WsController struct {
	controllers.BaseController
}

//创建用户并升级为ws
func (this *WsController) WsUpgrade() {
	sm := this.GetString("sm") //防请求伪造

	//防伪请求拦截
	if services.IsFakeRequest(sm) {
		logs.Error("IsFakeRequest 禁止请求伪造")
		this.AjaxFail(nil, "禁止请求伪造")
		return
	}

	uuid := this.GetString("uuid")
	name := this.GetString("name")
	avatar := this.GetString("avatar")
	gender,_ := this.GetInt("gender")
	types,_ := this.GetInt("type")

	logs.Info("ws connection:uuid:%s, name:%s, avatar:%s, gender:%s, types:%s", uuid, name, avatar, gender, types)

	//创建或修改用户信息
	user, err := models.UserCreate(uuid, name, avatar, uint(gender), uint(types))
	if err != nil {
		logs.Error("UserCreate", err.Error())
		this.AjaxFail(nil, err.Error())
		return
	}

	//升级为websocket连接
	services.ServeWs(user, this.Ctx.ResponseWriter, this.Ctx.Request)
}

//在线用户状况
func (this *WsController) OnlineUsers() {
	//获取在线用户
	onlines := services.UserClientService.GetOnlines()

	result := make([]helpers.HArr, 0)

	for k,v := range onlines  {
		result = append(result, helpers.HArr{
			"uid":k,
			"clients": len(v),
		})
	}

	this.AjaxSucc(result)
}

//历史记录
func (this *WsController) History() {
	uuid := this.GetString("uuid")
	lastId,_ := this.GetInt("last_id")
	size,_ := this.GetInt("size")

	//查询用户
	user := models.UserGetByUuid(uuid)

	if user.Id == 0 {
		this.AjaxFail(nil, "用户不存在")
		return
	}

	//查询记录
	result := services.CustomerMessageHistory(user.Id, uint(lastId), size)

	this.AjaxSucc(result)
}

//消息已读
func (this *WsController) Read() {
	uuid := this.GetString("uuid")

	//查询用户
	user := models.UserGetByUuid(uuid)

	if user.Id == 0 {
		this.AjaxFail(nil, "用户不存在")
		return
	}

	models.ChartReaded(user.Id)

	this.AjaxSucc(nil)
}

//客服已读
func (this *WsController) ManageRead() {
	uuid := this.GetString("uuid")
	chartId,_ := this.GetInt("chart_id")

	//查询用户
	user := models.UserGetByUuid(uuid)

	if user.Id == 0 {
		this.AjaxFail(nil, "用户不存在")
		return
	}

	models.ChartManagerReaded(user.Id, uint(chartId))

	this.AjaxSucc(nil)
}